package excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomMergeStrategy implements CellWriteHandler {

    private final int startCol;
    private Map<String, Integer> mergeStartRows;

    public CustomMergeStrategy(int startCol) {
        this.startCol = startCol;
        this.mergeStartRows = new HashMap<>();
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            return;
        }

        Sheet sheet = writeSheetHolder.getSheet();
        int rowIndex = cell.getRowIndex();
        int colIndex = cell.getColumnIndex();

        if (colIndex == startCol) {
            // 强制设置单元格格式为文本
            CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
            DataFormat dataFormat = sheet.getWorkbook().createDataFormat();
            cellStyle.setDataFormat(dataFormat.getFormat("@")); // 设置为文本格式
            cell.setCellStyle(cellStyle);

            String currentValue;
            switch (cell.getCellType()) {
                case STRING:
                    currentValue = cell.getStringCellValue().trim().replaceAll("^'", "");
                    break;
                case NUMERIC:
                    currentValue = String.valueOf(cell.getNumericCellValue());
                    break;
                default:
                    currentValue = "";
                    break;
            }

            if (mergeStartRows.containsKey(currentValue)) {
                int startRow = mergeStartRows.get(currentValue);
                CellRangeAddress cellRangeAddress = new CellRangeAddress(startRow, rowIndex, startCol, startCol);
                sheet.addMergedRegion(cellRangeAddress);
                mergeStartRows.remove(currentValue);
            } else {
                mergeStartRows.put(currentValue, rowIndex);
            }
        }
    }
}
